#!/usr/bin/perl

# Do simulation results file globbing
$outputdir = "/home/rumen/simulation1";
$analysisdir = "/home/rumen/cryptsim/analysis";
##$query = "K=.*RSM=3"; # .* means match any character (.) any number of times (*) in grep regex
$query = "K=.*_RSM=1_.*_T=7300.*"; 
if (!(-d $outputdir)) {
    mkdir($outputdir, 0777);
}
chdir($outputdir);
$args = "rm -fr $outputdir/ppdjob*";
system($args);

# Get all sweeps that match the query
opendir(DIR, $outputdir);
@files = grep { /$query/ } readdir(DIR);
closedir(DIR);
$sweepcnt=0;
foreach $f (@files) {
    print STDERR "Processing $f\n";
    $dir = $outputdir."/".$f;
    opendir(DIR, $dir);    
    @clonesfiles = grep { /clones$/ } readdir(DIR);
    closedir(DIR);
    # go to the folder of that sweep
    chdir($dir);
    foreach $cf (@clonesfiles) {
	@r = split (/\./, $cf);
	# Prepare postprocessing job for that replicate
	$sweepcnt++;
	open(out2, ">$outputdir/ppdjob$sweepcnt.sh");
	print out2 "#!/bin/bash\n";		

	# $number_of_biopsies_to_sample = $ARGV[1]; # Quicker results
# 	$number_of_biopsies_schedule;
# 	$number_of_biopsies_schedule[0] = $number_of_biopsies_to_sample;
# 	$biopsy_size_x = $ARGV[2]; # width
# 	$biopsy_size_y = $ARGV[3]; # length (~2x higher than width)
# 	$detection_cutoff = $ARGV[4];
# 	$distogram_output = 0; # Set to 1 to output distograms
# # Seed the random number generator
# 	srand ($ARGV[5]);
# it seems that seeding the generator with 0 will always sample the grid at the same biopsy locations across all sweeps
	print out2 "perl $analysisdir/postprocessing.of.simulation.run.calculate.biopsy.divergence.over.time.Apr4.pl $dir/".$r[0]." 12 10 10 0.05 0\n";
	close(out2);			    
    }
}



open(out,">$outputdir/submit.post.processing.calculate.divergence.pl");
print out q(#!/usr/bin/perl

	    if(defined($ARGV[1])){
		for($i=$ARGV[0]; $i<=$ARGV[1]; $i++){
		    $args = "qsub -q all.q -p -100 -cwd ppdjob$i.sh";
		    system($args);    
		}
	    } else {
		$args = "qsub -q all.q -p -100 -cwd ppdjob".$ARGV[0].".sh";
		system($args);    
	    }
	    );
close out;

